package com.ambitor.ipro.app.count;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.ipro.util.LocalConnectionUtils;
import com.ambitor.ipro.util.Utils;

public class CountDaySumApp {

	private static final Logger logger = LoggerFactory
			.getLogger(CountDaySumApp.class);

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws ParseException, SQLException {
		String startDateStr = CountPropertiesReader.getString("START_DATE");
		String endDateStr = CountPropertiesReader.getString("END_DATE");

		Date startDate = null;
		Date endDate = null;
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (StringUtils.isBlank(startDateStr)) {
			calendar.add(Calendar.DATE, -1); // 得到前一天
			startDate = calendar.getTime();
		} else {
			startDate = sdf.parse(startDateStr);
		}

		if (StringUtils.isBlank(endDateStr)) {
			endDate = new Date();
		} else {
			endDate = sdf.parse(endDateStr);
		}

		Connection conn = getConn();
		int minus = Utils.daysBetween(startDate, endDate);
		calendar.setTime(startDate);
		for (int i = 0; i < minus; i++) {
			Date clctDate = calendar.getTime();
			CountDaySum countDaySum = new CountDaySum(conn, clctDate);
			try {
				countDaySum.parseRefererAndSum();
			} catch (Exception e) {
				logger.error("parseRefererAndSum出现异常", e);
			}
			calendar.add(Calendar.DATE, 1);
		}
		conn.close();
	}

	private static Connection getConn() throws SQLException {
		Connection conn = null;
		conn = LocalConnectionUtils.getConnection();
		return conn;
	}
}
